<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\finance\PayablePrintingPlateModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PrintingPlate extends Controller
{
    /**
     * 打板列表
     */
    public function list(Request $request)
    {
        $date_start = $request->input('date_start', '');
        $date_end = $request->input('date_end', '');
        $agent_id = $request->input('agent_id', 0);
        $take_order_sn = $request->input('take_order_sn', '');
        $plate_number = $request->input('plate_number', '');
        $status = $request->input('status', 0);
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayablePrintingPlateModel::with(['createAdmin', 'agent', 'takeOrder']);

        if ($date_start && $date_end) {
            $query->whereBetween('date', [$date_start, $date_end]);
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        if ($take_order_sn) {
            $query->whereHas('takeOrder', function ($query) use ($take_order_sn) {
                $query->where('sn', 'like', "%{$take_order_sn}%");
            });
        }

        if ($plate_number) {
            $query->where('plate_number', 'like', "%{$plate_number}%");
        }

        if ($status) {
            $query->where('status', $status);
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()
            ->map(function($item) {
                return [
                    'id' => $item->id,
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'date' => $item->date,
                    'take_order_id' => $item->take_order_id,
                    'take_order_sn' => $item->takeOrder->sn ?? '',
                    'plate_number' => $item->plate_number,
                    'weight' => $item->weight,
                    'plate_unit_price' => $item->plate_unit_price,
                    'plate_amount' => $item->plate_amount,
                    'security_check_unit_price' => $item->security_check_unit_price,
                    'security_check_amount' => $item->security_check_amount,
                    'safety_net_unit_price' => $item->safety_net_unit_price,
                    'safety_net_amount' => $item->safety_net_amount,
                    'packaging_film_amount' => $item->packaging_film_amount,
                    'black_film_amount' => $item->black_film_amount,
                    'scanning_amount' => $item->scanning_amount,
                    'total_amount' => $item->total_amount,
                    'remarks' => $item->remarks,
                    'status' => $item->status,
                    'status_name' => PayablePrintingPlateModel::STATUS_LIST[$item->status] ?? '',
                    'pay_amount' => $item->pay_amount,
                    'created_admin_id' => $item->created_admin_id,
                    'created_admin_name' => $item->createAdmin->name ?? '',
                    'created_at' => $item->created_at->format('Y-m-d H:i:s')
                ];
            });

        // 计算总金额
        $totalAmount = $query->sum('total_amount');

        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加打板记录
     */
    public function add(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'agent_id' => 'required|integer|min:1',
            'date' => 'required|date',
            'take_order_sn' => 'required|string',
            'plate_number' => 'required|string',
            'weight' => 'required|numeric|min:0',
            'plate_unit_price' => 'required|numeric|min:0',
            'security_check_unit_price' => 'numeric|min:0',
            'safety_net_unit_price' => 'numeric|min:0',
            'packaging_film_amount' => 'numeric|min:0',
            'black_film_amount' => 'numeric|min:0',
            'scanning_amount' => 'numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        // 验证提单是否存在
        $takeOrder = TakeOrderModel::where('sn', $params['take_order_sn'])->first();
        if (!$takeOrder) {
            return $this->error('提单不存在');
        }

        try {
            $weight = $params['weight'];
            $plateUnitPrice = $params['plate_unit_price'];
            $securityCheckUnitPrice = $params['security_check_unit_price'] ?? 0;
            $safetyNetUnitPrice = $params['safety_net_unit_price'] ?? 0;
            
            // 计算各项金额
            $plateAmount = $weight * $plateUnitPrice;
            $securityCheckAmount = $weight * $securityCheckUnitPrice;
            $safetyNetAmount = $weight * $safetyNetUnitPrice;
            $packagingFilmAmount = $params['packaging_film_amount'] ?? 0;
            $blackFilmAmount = $params['black_film_amount'] ?? 0;
            $scanningAmount = $params['scanning_amount'] ?? 0;
            
            // 计算合计金额
            $totalAmount = $plateAmount + $securityCheckAmount + $safetyNetAmount + 
                           $packagingFilmAmount + $blackFilmAmount + $scanningAmount;

            $plate = new PayablePrintingPlateModel();
            $plate->agent_id = $params['agent_id'];
            $plate->date = $params['date'];
            $plate->take_order_id = $takeOrder->id;
            $plate->plate_number = $params['plate_number'];
            $plate->weight = $weight;
            $plate->plate_unit_price = $plateUnitPrice;
            $plate->plate_amount = $plateAmount;
            $plate->security_check_unit_price = $securityCheckUnitPrice;
            $plate->security_check_amount = $securityCheckAmount;
            $plate->safety_net_unit_price = $safetyNetUnitPrice;
            $plate->safety_net_amount = $safetyNetAmount;
            $plate->packaging_film_amount = $packagingFilmAmount;
            $plate->black_film_amount = $blackFilmAmount;
            $plate->scanning_amount = $scanningAmount;
            $plate->total_amount = $totalAmount;
            $plate->remarks = $params['remarks'] ?? '';
            $plate->status = PayablePrintingPlateModel::STATUS_UNPAID;
            $plate->pay_amount = 0;
            $plate->created_admin_id = $request->get('auth')->id;
            $plate->save();

            return $this->success($plate);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新打板记录
     */
    public function update(Request $request, $id)
    {
        $plate = PayablePrintingPlateModel::find($id);
        if (!$plate) {
            return $this->error('打板记录不存在');
        }

        $params = $request->all();
        $validator = Validator::make($params, [
            'agent_id' => 'required|integer|min:1',
            'date' => 'required|date',
            'take_order_sn' => 'required|string',
            'plate_number' => 'required|string',
            'weight' => 'required|numeric|min:0',
            'plate_unit_price' => 'required|numeric|min:0',
            'security_check_unit_price' => 'numeric|min:0',
            'safety_net_unit_price' => 'numeric|min:0',
            'packaging_film_amount' => 'numeric|min:0',
            'black_film_amount' => 'numeric|min:0',
            'scanning_amount' => 'numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        // 验证提单是否存在
        $takeOrder = TakeOrderModel::where('sn', $params['take_order_sn'])->first();
        if (!$takeOrder) {
            return $this->error('提单不存在');
        }

        try {
            $weight = $params['weight'];
            $plateUnitPrice = $params['plate_unit_price'];
            $securityCheckUnitPrice = $params['security_check_unit_price'] ?? 0;
            $safetyNetUnitPrice = $params['safety_net_unit_price'] ?? 0;
            
            // 计算各项金额
            $plateAmount = $weight * $plateUnitPrice;
            $securityCheckAmount = $weight * $securityCheckUnitPrice;
            $safetyNetAmount = $weight * $safetyNetUnitPrice;
            $packagingFilmAmount = $params['packaging_film_amount'] ?? 0;
            $blackFilmAmount = $params['black_film_amount'] ?? 0;
            $scanningAmount = $params['scanning_amount'] ?? 0;
            
            // 计算合计金额
            $totalAmount = $plateAmount + $securityCheckAmount + $safetyNetAmount + 
                           $packagingFilmAmount + $blackFilmAmount + $scanningAmount;

            $plate->agent_id = $params['agent_id'];
            $plate->date = $params['date'];
            $plate->take_order_id = $takeOrder->id;
            $plate->plate_number = $params['plate_number'];
            $plate->weight = $weight;
            $plate->plate_unit_price = $plateUnitPrice;
            $plate->plate_amount = $plateAmount;
            $plate->security_check_unit_price = $securityCheckUnitPrice;
            $plate->security_check_amount = $securityCheckAmount;
            $plate->safety_net_unit_price = $safetyNetUnitPrice;
            $plate->safety_net_amount = $safetyNetAmount;
            $plate->packaging_film_amount = $packagingFilmAmount;
            $plate->black_film_amount = $blackFilmAmount;
            $plate->scanning_amount = $scanningAmount;
            $plate->total_amount = $totalAmount;
            $plate->remarks = $params['remarks'] ?? '';
            $plate->save();

            return $this->success($plate);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除打板记录
     */
    public function delete($id)
    {
        $plate = PayablePrintingPlateModel::find($id);
        if (!$plate) {
            return $this->error('打板记录不存在');
        }

        if ($plate->status != PayablePrintingPlateModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $plate->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取打板详情
     */
    public function detail($id)
    {
        $plate = PayablePrintingPlateModel::with(['createAdmin', 'agent', 'takeOrder'])->find($id);
        if (!$plate) {
            return $this->error('打板记录不存在');
        }

        $data = $plate->toArray();
        $data['agent_name'] = $plate->agent->name ?? '';
        $data['take_order_sn'] = $plate->takeOrder->sn ?? '';
        $data['status_name'] = PayablePrintingPlateModel::STATUS_LIST[$plate->status] ?? '';
        $data['created_admin_name'] = $plate->createAdmin->name ?? '';

        return $this->success($data);
    }

    /**
     * 设置付款状态
     */
    public function setPaid(Request $request, $id)
    {
        $plate = PayablePrintingPlateModel::find($id);
        if (!$plate) {
            return $this->error('打板记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'pay_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $payAmount = $request->input('pay_amount');
        $totalAmount = $plate->total_amount;

        // 设置付款状态
        if ($payAmount >= $totalAmount) {
            $status = PayablePrintingPlateModel::STATUS_PAID;
            $payAmount = $totalAmount; // 确保支付金额不超过总金额
        } elseif ($payAmount > 0) {
            $status = PayablePrintingPlateModel::STATUS_PART_PAID;
        } else {
            $status = PayablePrintingPlateModel::STATUS_UNPAID;
        }

        try {
            $plate->pay_amount = $payAmount;
            $plate->status = $status;
            $plate->save();

            return $this->success($plate);
        } catch (\Exception $e) {
            return $this->error('设置付款状态失败：' . $e->getMessage());
        }
    }
} 